package com.etc.zmall.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.etc.util.AjaxUploadResponse;
import com.google.gson.Gson;

/**
 * Servlet implementation class AjaxGoodsUpload
 */
@WebServlet("/agu.do")
@MultipartConfig
public class AjaxGoodsUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AjaxGoodsUpload() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("applicaton/json;charset=utf-8");
		//
		PrintWriter out = response.getWriter();

		// 3=> 得到上传文件
		Part part = request.getPart("file");
		// 得到实际路径
		String path = request.getServletContext().getRealPath("/picture/");

		System.out.println("path :" + path);

		String picpath = part.getSubmittedFileName();
		// 4= > 写入目标位置(写到tomcat目录webapps/当前工程目录下)
		part.write(path + part.getSubmittedFileName());

		AjaxUploadResponse aur = new AjaxUploadResponse(0, "success", picpath);

		// gson转换
		Gson g = new Gson();
		String str = g.toJson(aur);

		// printwriter
		out.print(str);

		out.close();

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
